#pragma once

struct M2ModelCache
{
	std::string szModelName;
	Vertex3FT** vertices;
	ui32* nVertices;
	std::vector<std::string> textures;
	i32 references;
	ui32 nPasses;
	bool useable;
};

class M2Cache : public Singleton<M2Cache>
{
	Mutex m_cacheLock;
	std::map<std::string, M2ModelCache*> m_cache;
public:
	M2Cache()
	{
	}

	M2ModelCache* GetCache(std::string szModelName)
	{
		if(m_cache[szModelName] && m_cache[szModelName]->useable)
		{
			m_cache[szModelName]->references++;
			return m_cache[szModelName];
		}
		else
			return 0;
	}

	void AddCache(std::string szModelName, M2ModelCache* pCache)
	{
		m_cacheLock.Acquire();
		pCache->useable = true;
		m_cache[szModelName] = pCache;
		m_cacheLock.Release();
	}

	void RemoveCache(std::string szModelName)
	{
		m_cacheLock.Acquire();
		if(m_cache[szModelName] && m_cache[szModelName]->useable)
		{
			M2ModelCache* c = m_cache[szModelName];
			--c->references;
			if(c->references <= 0)
			{
				c->useable = false;
				delete [] c->nVertices;
				for(ui32 i = 0; i < c->nPasses; ++i)
				{
					if(c->vertices[i])
						delete [] c->vertices[i];
				}
			}
		}
		m_cacheLock.Release();
	}
};

#define sM2Cache (*M2Cache::GetInstance())